package com.lagou.niancheng.biz.server;

import com.lagou.niancheng.biz.api.ApiException;
import com.lagou.niancheng.biz.api.UserApi;
import com.lagou.niancheng.biz.api.entity.User;
import com.lagou.niancheng.rpc.server.spring.ServiceProvider;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户api实现类
 *
 * @author 大犬
 * @date 2020/4/27
 */
@Service
@ServiceProvider
public class UserApiImpl implements UserApi {

    private Map<String, User> userMap;

    @PostConstruct
    public void init() {
        userMap = new ConcurrentHashMap<>(10);
    }

    @Override
    public String insertUser(User user) {
        // 参数校验
        checkInsertUserParam(user);
        String id = UUID.randomUUID().toString().replaceAll("-", "");
        user.setId(id);
        userMap.put(id, user);
        return id;
    }


    @Override
    public void deleteUser(String userId) {
        // 参数校验
        checkDeleteUserParam(userId);
        userMap.remove(userId);
    }


    @Override
    public void updateUser(User user) {
        // 参数校验
        checkUpdateUserParam(user);
        userMap.put(user.getId(), user);
    }


    @Override
    public List<User> listAllUsers() {
        return new ArrayList<>(userMap.values());
    }


    private void checkDeleteUserParam(String userId) {
        if (userId == null) {
            throw buildError(BizErrorCode.PARAM_CANNOT_BE_NULL, "用户id");
        }
        if (!userMap.containsKey(userId)) {
            throw buildError(BizErrorCode.USER_IS_NOT_EXIST);
        }
    }

    private void checkUpdateUserParam(User user) {
        if (user.getId() == null) {
            throw buildError(BizErrorCode.PARAM_CANNOT_BE_NULL, "用户id");
        }
        if (!userMap.containsKey(user.getId())) {
            throw buildError(BizErrorCode.USER_IS_NOT_EXIST);
        }
        if (user.getUsername() == null) {
            throw buildError(BizErrorCode.PARAM_CANNOT_BE_NULL, "用户名称");
        }
    }

    private void checkInsertUserParam(User user) {

        if (user.getUsername() == null) {
            throw buildError(BizErrorCode.PARAM_CANNOT_BE_NULL, "用户名称");
        }
    }

    private ApiException buildError(BizErrorCode errorCode, String... params) {
        if (params == null || params.length == 0) {
            return new ApiException()
                    .setErrorCode(errorCode.getErrorCode())
                    .setErrorMsg(errorCode.getErrorMsg());
        }
        return new ApiException()
                .setErrorCode(errorCode.getErrorCode())
                .setErrorMsg(MessageFormat.format(errorCode.getErrorMsg(), params));
    }

}
